<?php
namespace Particle\Core;
use Particle\Core as Core;
/**
 * @package Particle
 * @category Core
 * @author dertin
 * @abstract
 *  
 **/

abstract class Controller {

    protected $_view;
    protected $_args;
    protected $_model;
    protected $_modelAddons;
    
    private static $controller;
    private static $method;

    protected function __construct() {
        
            self::$controller = Core\App::getInstance()->getAppController();
            self::$method = Core\App::getInstance()->getAppMethod();
            
            $this->_args = Core\App::getInstance()->getAppArgs();
                        
            $request = Core\App::getInstance()->getAppRequest();
            
            $this->_view = new Core\View(self::$controller, self::$method, $request);
            
            $this->_model = $this->loadModel(false, true);
            
    }
    
    protected final function loadModel($modelName = false, $noException = false) {
        
        if ($modelName== FALSE || !is_string($modelName) || empty($modelName)) {
            $modelName = self::$controller;
        }
        
        $modelClass = $modelName . 'Model';
        $pathModel = APP_PATH . 'models' . DS . $modelClass . '.php';
        
        
        if (is_readable($pathModel)) {

            require_once $pathModel;
            
            $modelNamesapce =  'Particle\\Apps\\' . $modelClass;
            
            if (class_exists($modelNamesapce, false)) {

                $modelInstance = new $modelNamesapce;
                              
                return $modelInstance;
            } else {

                if (!$noException) {

                    throw new \Exception('Bad Model');
                    
                } else {
                    return false;
                }
                
            }
        } else {
            if (!$noException) {
                
                    throw new \Exception('Error Model');
                
            } else {
                return false;
            }
        }
        
    }
    
}